package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.QiniuUtil;
import cn.stylefeng.guns.sys.modular.system.entity.Task;
import cn.stylefeng.guns.sys.modular.system.entity.TaskFlow;
import cn.stylefeng.guns.sys.modular.system.entity.TaskStatus;
import cn.stylefeng.guns.sys.modular.system.model.params.ProjectParam;
import cn.stylefeng.guns.sys.modular.system.model.params.TaskParam;
import cn.stylefeng.guns.sys.modular.system.service.TaskService;
import cn.stylefeng.guns.sys.modular.system.service.TaskStatusService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.*;


/**
 * 控制器
 *
 * @author jiangge
 * @Date 2020-09-10 22:11:50
 */
@Controller
@RequestMapping("/task")
public class TaskController extends BaseController {

    private String PREFIX = "/modular/system/task";

    @Autowired
    private TaskService taskService;
    @Resource
    private TaskStatusService taskStatusService;

    /**
     * 跳转到主页面
     *
     * @author jiangge
     * @Date 2020-09-10
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/task.html";
    }

    /**
     * 督导开发任务页面
     *
     * @author jiangge
     * @Date 2020-09-10
     */
    @RequestMapping("/steerTask")
    public String steerTask(Integer id, ModelMap map) {


        //获取当前用户角色列表
        LoginUser user = LoginContextHolder.getContext().getUser();
        int role = 0;
        List<Long> roleList = user.getRoleList();
        for (Long name:roleList) {
            if(name.longValue()==new Long("1283292980305018882").longValue()){//督导
                TaskStatus status=taskStatusService.getOne(new QueryWrapper<TaskStatus>().eq("pro_id",id).eq("task_id",56));
                if(ToolUtil.isEmpty(status)){
                    status=new TaskStatus();
                    status.setProId(id);
                    status.setTaskId(56);
                    status.setStatus(1);
                    status.setTaskName("营业执照名称");
                    status.setCreateId(user.getId());
                    taskStatusService.save(status);

                }
                TaskStatus statuss=taskStatusService.getOne(new QueryWrapper<TaskStatus>().eq("pro_id",id).eq("task_id",57));
                if(ToolUtil.isEmpty(statuss)){
                    statuss=new TaskStatus();
                    statuss.setProId(id);
                    statuss.setTaskId(57);
                    statuss.setStatus(1);
                    statuss.setTaskName("统一社会信用代码");
                    statuss.setCreateId(user.getId());
                    taskStatusService.save(statuss);

                }

                TaskStatus frxm=taskStatusService.getOne(new QueryWrapper<TaskStatus>().eq("pro_id",id).eq("task_id",59));
                if(ToolUtil.isEmpty(frxm)){
                    frxm=new TaskStatus();
                    frxm.setProId(id);
                    frxm.setTaskId(59);
                    frxm.setStatus(1);
                    frxm.setTaskName("法人姓名");
                    frxm.setCreateId(user.getId());
                    taskStatusService.save(frxm);
                }
                TaskStatus sfz=taskStatusService.getOne(new QueryWrapper<TaskStatus>().eq("pro_id",id).eq("task_id",60));
                if(ToolUtil.isEmpty(sfz)){
                    sfz=new TaskStatus();
                    sfz.setProId(id);
                    sfz.setTaskId(60);
                    sfz.setStatus(1);
                    sfz.setTaskName("法人身份证号");
                    sfz.setCreateId(user.getId());
                    taskStatusService.save(sfz);
                }
                role = 1;
            }else if(name.longValue()==new Long("1307580056085250050").longValue()){//网上建店负责人
                role = 2;
            }
        }
        map.put("id", id);
        map.put("role", role);
        map.put("name", user.getName());
        map.put("list", taskList(id));
        return PREFIX + "/steerTask.html";
    }
    /**
     * 督导开发任务页面
     *
     * @author jiangge
     * @Date 2020-09-10
     */
    @RequestMapping("/steerTaskAdmin")
    public String steerTaskAdmin(Integer id, ModelMap map) {
        //获取当前用户角色列表
        LoginUser user = LoginContextHolder.getContext().getUser();
        int role = 0;
        List<Long> roleList = user.getRoleList();
        for (Long name:roleList) {
            if(name.longValue()==new Long("1283292980305018882").longValue()){//督导
                role = 1;
            }else if(name.longValue()==new Long("1307580056085250050").longValue()){//网上建店负责人
                role = 2;
            }
        }
        TaskStatus status=taskStatusService.getOne(new QueryWrapper<TaskStatus>().eq("pro_id",id).eq("task_id",56));
        if(ToolUtil.isEmpty(status)){
            status=new TaskStatus();
            status.setProId(id);
            status.setTaskId(56);
            status.setStatus(1);
            status.setTaskName("营业执照名称");
            status.setCreateId(user.getId());
            taskStatusService.save(status);

        }
        TaskStatus statuss=taskStatusService.getOne(new QueryWrapper<TaskStatus>().eq("pro_id",id).eq("task_id",57));
        if(ToolUtil.isEmpty(statuss)){
            statuss=new TaskStatus();
            statuss.setProId(id);
            statuss.setTaskId(57);
            statuss.setStatus(1);
            statuss.setTaskName("统一社会信用代码");
            statuss.setCreateId(user.getId());
            taskStatusService.save(statuss);

        }


        TaskStatus frxm=taskStatusService.getOne(new QueryWrapper<TaskStatus>().eq("pro_id",id).eq("task_id",59));
        if(ToolUtil.isEmpty(frxm)){
            frxm=new TaskStatus();
            frxm.setProId(id);
            frxm.setTaskId(59);
            frxm.setStatus(1);
            frxm.setTaskName("法人姓名");
            frxm.setCreateId(user.getId());
            taskStatusService.save(frxm);
        }
        TaskStatus sfz=taskStatusService.getOne(new QueryWrapper<TaskStatus>().eq("pro_id",id).eq("task_id",60));
        if(ToolUtil.isEmpty(sfz)){
            sfz=new TaskStatus();
            sfz.setProId(id);
            sfz.setTaskId(60);
            sfz.setStatus(1);
            sfz.setTaskName("法人身份证号");
            sfz.setCreateId(user.getId());
            taskStatusService.save(sfz);
        }
        map.put("id", id);
        map.put("role", role);
        map.put("name", user.getName());
        map.put("list", taskList(id));
        return PREFIX + "/steerTaskAdmin.html";
    }

    /**
     * 工程开发任务页面
     *
     * @author jiangge
     * @Date 2020-09-10
     */
    @RequestMapping("/projectTask")
    public String projectTask(Integer id, ModelMap map) {
        map.put("id", id);
        map.put("list", taskList(id));
        return PREFIX + "/projectTask.html";
    }
    /**
     * 工程开发任务页面
     *
     * @author jiangge
     * @Date 2020-09-10
     */
    @RequestMapping("/projectTaskAdmin")
    public String projectTaskAdmin(Integer id, ModelMap map) {
        map.put("id", id);
        map.put("list", taskList(id));
        return PREFIX + "/projectTaskAdmin.html";
    }

    /**
     * 编辑页面
     *
     * @author jiangge
     * @Date 2020-09-10
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/task_edit.html";
    }

    /**
     * 新增接口
     *
     * @author jiangge
     * @Date 2020-09-10
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(TaskParam taskParam) {
        this.taskService.add(taskParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author jiangge
     * @Date 2020-09-10
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(TaskParam taskParam) {
        this.taskService.update(taskParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author jiangge
     * @Date 2020-09-10
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(TaskParam taskParam) {
        this.taskService.delete(taskParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author jiangge
     * @Date 2020-09-10
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(TaskParam taskParam) {
        Task detail = this.taskService.getById(taskParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author jiangge
     * @Date 2020-09-10
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(TaskParam taskParam) {
        return this.taskService.findPageBySpec(taskParam);
    }


    /**
     * 新增任务信息
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/addRent")
    public ResponseData addRent(@RequestBody List<TaskStatus> taskStatus) throws ParseException {
        taskService.addRent(taskStatus);
        return ResponseData.success();
    }

    /**
     * 确认到货修改
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/editDh")
    public ResponseData editDh(Integer proId) {
        taskService.editDh(proId);
        return ResponseData.success();
    }

    /**
     * 新增任务信息
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/addRentAdmin")
    public ResponseData addRentAdmin(@RequestBody List<TaskStatus> taskStatus) throws ParseException {
        return taskService.addRentAdmin(taskStatus);
    }


    /**
     * 上传图片
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/uploads")
    //@PostMapping("/uploads")
    public Map<String, Object> uploads(@RequestPart("file") MultipartFile file, Integer proId, Integer taskId) {

        return QiniuUtil.uploadFile(file, null);
    }

    /**
     * 督导/工程部任务数据
     */
    public String taskList(Integer proId) {
        ArrayList<TaskStatus> taskStatuses = (ArrayList) taskService.taskList(proId);
        String listJson = JSONArray.toJSONString(new ArrayList[]{taskStatuses});
        return listJson;
    }

    /**
     * 流程进度
     * @param projectParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/productList")
    public LayuiPageInfo productList(ProjectParam projectParam) {
        return this.taskService.productList(projectParam);
    }

    /**
     * 流程进度
     * @param projectParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/yingYunQuery")
    public LayuiPageInfo yingYunQuery(ProjectParam projectParam) {
        return this.taskService.yingYunQuery(projectParam);
    }


    /**
     * 督导未完成列表
     * @param
     * @return
     */
    @ResponseBody
    @GetMapping("/ddList")
    public List<Task> ddList(Integer proId) {
        return this.taskService.ddList(proId);
    }

    /**
     * 工程未完成列表
     * @param
     * @return
     */
    @ResponseBody
    @GetMapping("/ggList")
    public List<Task> ggList(Integer proId) {
        return this.taskService.ggList(proId);
    }

    /**
     * 督导确认完工
     * @param proId
     * @param taskId
     * @return
     */
    @ResponseBody
    @PostMapping("/endSave")
    public int endSave(Integer proId, Integer taskId){

        return taskService.endSave(proId, taskId);
    }

    /**
     * 网上建店审核
     * @return
     */
    @ResponseBody
    @PostMapping("/audit")
    public int audit(TaskStatus status){

        LoginUser loginuser = LoginContextHolder.getContext().getUser();
        status.setCreateId(loginuser.getId());
        status.setCreateName(loginuser.getName());

        TaskFlow taskFlow = new TaskFlow();
        taskFlow.setProId(status.getProId());
        taskFlow.setTaskId(status.getTaskId());
        taskFlow.setStatus(status.getStatus());//1审核通过,0审核不通过
        taskFlow.setTaskName(status.getTaskName());
        taskFlow.setCreateUser(LoginContextHolder.getContext().getUserId());
        taskFlow.setCreateTime(new Date());

        return taskService.insertRent(status, taskFlow);
    }


    /**
     * 收银系统修改状态
     * @return
     */
    @ResponseBody
    @PostMapping("/cashierSave")
    public ResponseData cashierSave(TaskStatus taskStatus){
        return taskService.cashierSave(taskStatus);
    }

    /**
     * 上传文件
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public Map<String, Object> models(@RequestPart("file") MultipartFile file, HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        // MultipartFile file＝null;
        //BufferedOutputStream stream = null;
        Map<String, Object> msg = new HashMap<>(16);
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            //String filePath = "D:/pictureUpload/project/upload/";
            //File targetFile = new File(filePath);
            //如果目录不存在，创建目录
            //if (!targetFile.exists()) {
            //    targetFile.mkdirs();
            //}
            if (!file.isEmpty()) {
                /*try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(filePath + file.getOriginalFilename()));
                    stream.write(bytes);//写入
                    stream.close();
                    //上传成功后，将可以访问的完整路径返回
                    String fullImgpath = "/pictureUpload/project/upload/" + file.getOriginalFilename();
                    Map<String, Object> data = new HashMap<>(16);
                    msg.put("code", 0);
                    msg.put("msg", "上传成功");
                    msg.put("data", data);
                    data.put("src", fullImgpath);

                    data.put("title", StringUtils.substringAfterLast(fullImgpath, "/"));
                } catch (Exception e) {
                    e.printStackTrace();
                    msg.put("code", 1);
                    msg.put("msg", "上传失败");
                }*/
                msg = QiniuUtil.uploadFile(file, null);
            }
        }

        return msg;
    }

    /**
     * 修改任务信息
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/editRent")
    public ResponseData editRent(@RequestBody List<TaskStatus> taskStatus) throws ParseException {
        taskService.editRent(taskStatus);
        return ResponseData.success();
    }

}

